package com.yzs.base.utils

import android.content.Context
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.facade.service.SerializationService
import com.google.gson.Gson
import java.lang.reflect.Type

/**
 * author : yzs
 * time   : 2021/06/28
 * desc   : 用于 ARouter 序列化传参
 */

@Route(path = "/service/json")
class JsonServiceImpl : SerializationService {
    private lateinit var mGson: Gson

    override fun <T : Any?> json2Object(text: String?, clazz: Class<T>?): T {
        checkJson()
        return mGson.fromJson(text, clazz)
    }

    override fun init(context: Context?) {
        mGson = Gson()
    }

    override fun object2Json(instance: Any?): String {
        checkJson()
        return mGson.toJson(instance)
    }

    override fun <T : Any?> parseObject(input: String?, clazz: Type?): T {
        checkJson()
        return mGson.fromJson(input, clazz)
    }

    private fun checkJson() {
        if (mGson == null) mGson = Gson()
    }
}